/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 驿站代收开通审核
 */
import React, { useRef, useCallback, useEffect, useState } from 'react';
import {
  getApplicationList,
  changeInfoDetailed,
  changeInfoReject,
  getYzLogList,
} from '@/services/operatorManagement';
import ProTable from '@ant-design/pro-table';
import DragTable from '@/components/DragTable';
import { useSelector } from 'umi';
import type { ConnectState } from '@/models/connect';
import { Input, Button, Drawer, Spin, Row, Col, message, Divider, Popover, Space } from 'antd';
import ProDescriptions from '@ant-design/pro-descriptions';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { recordColumns } from '../types/ChangeInfo.d';
import type { TableListItem, YzTableList, inn_stat } from '../types/ChangeInfo.d';
import KbRefuseModal from './RefuseForm';

interface ChangeInfoTableType {
  activeKey: string;
  type: string;
}

interface record {
  inn_info: inn_stat;
  inn_stat: YzTableList;
}

const ChangeInfoTable = ({ type, activeKey }: ChangeInfoTableType) => {
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const actionRef = useRef<ActionType>();
  const [record, setRecord] = useState<record>({} as any);
  const [visible, setVisible] = useState<boolean>(false);
  const [formVisible, setFormVisible] = useState<boolean>(false);
  const [submitLoading, setSubmitLoading] = useState<boolean>(false);
  const [showButton, setShowButton] = useState<boolean>(false);
  const [yzLogList, setYzLogList] = useState<any>({ page: 1, hasNextPage: true, list: [] });
  const activeKeyList = {
    check: '1',
    adopt: '2',
    disable: '3',
  };

  const getYzLog = (values: any) => {
    const { page, list } = yzLogList;
    getYzLogList({ ...values, page, size: 10 }).then(({ code, data, msg }: any) => {
      let pages = page,
        logList = list,
        hasNext = true;
      if (code == 0) {
        if (Math.ceil(data.total / 10) > page) {
          pages += 1;
          hasNext = true;
        } else {
          hasNext = false;
        }
        logList = [...logList, ...data.list];
      } else {
        message.error(msg);
      }
      setYzLogList({ ...yzLogList, hasNextPage: hasNext, list: logList, page: pages });
    });
  };

  const handleDetail = useCallback((values: any) => {
    setSubmitLoading(true);
    if (values.page_turn) {
      values.type = activeKeyList[type];
    }
    changeInfoDetailed(values).then((res) => {
      const { code, data, msg } = res;
      if (code == 0) {
        setVisible(true);
        setRecord(data);
        getYzLog({ cm_id: data.inn_info.cm_id });
        if (type == 'check') setShowButton(true);
      } else {
        message.error(msg);
      }
      setSubmitLoading(false);
    });
  }, []);

  const onClose = () => {
    setVisible(false);
  };

  const handleHideMoal = () => {
    setFormVisible(false);
  };

  const handleSubmit = (values: any) => {
    const id = record.inn_info.id;
    changeInfoReject({ ...values, id }).then((res: any) => {
      const { code, msg } = res;
      if (code == 0) {
        setShowButton(false);
        handleHideMoal();
        message.success(msg);
        actionRef.current?.reload();
        changeInfoDetailed({ id });
      } else {
        message.error(msg);
      }
    });
  };

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '',
      hideInTable: true,
      dataIndex: 'keywords',
      renderFormItem: () => {
        return <Input name='keywords' placeholder='请输入id/手机号/名称' />;
      },
    },
    {
      title: 'id',
      width: 40,
      dataIndex: 'id',
      align: 'center',
      search: false,
      ellipsis: true,
    },
    {
      title: '驿站名称',
      dataIndex: 'inn_name',
      align: 'center',
      width: 60,
      search: false,
      ellipsis: true,
    },
    {
      title: '驿站地址',
      dataIndex: 'concat_location',
      align: 'center',
      width: 100,
      search: false,
      ellipsis: true,
    },
    {
      title: '驿站账号',
      dataIndex: 'phone',
      align: 'center',
      width: 60,
      search: false,
      ellipsis: true,
    },
    {
      title: '联系电话',
      dataIndex: 'concat_phone',
      align: 'center',
      width: 60,
      search: false,
      ellipsis: true,
      hideInTable: type === 'blackList',
    },
    {
      title: '实名认证',
      dataIndex: 'is_auth_realname',
      align: 'center',
      search: false,
      ellipsis: true,
      width: 60,
      render: (_, data) => {
        return <>{data.is_auth_realname === 1 ? '已实名' : '未实名'}</>;
      },
    },
    {
      title: '经营信息认证',
      dataIndex: 'business_audit_status',
      align: 'center',
      width: 60,
      search: false,
      ellipsis: true,
      render: (_, data) => {
        return (
          <>
            {data.business_audit_status === 0
              ? '未提交'
              : data.business_audit_status === 1
              ? '待审核'
              : data.business_audit_status === 2
              ? '未通过'
              : data.business_audit_status === 3
              ? '已通过'
              : '-'}
          </>
        );
      },
    },
    {
      title: '注册时间',
      dataIndex: 'register_time',
      align: 'center',
      width: 70,
      search: false,
      ellipsis: true,
    },
    {
      title: '修改时间',
      dataIndex: 'apply_time',
      align: 'center',
      width: 70,
      search: false,
      ellipsis: true,
    },
    {
      title: '品牌',
      dataIndex: 'brand_cn',
      align: 'center',
      width: 50,
      search: false,
      ellipsis: true,
    },
    {
      title: '审核信息',
      dataIndex: 'operator_phone',
      align: 'center',
      width: 90,
      search: false,
      ellipsis: true,
      hideInTable: type == 'check',
      render: (_, data) => {
        return (
          <>
            <div>{_}</div>
            <Popover content={data.reject_reason_desc}>{data.reject_reason_desc}</Popover>
            <Popover content={data.approve_time}>{data.approve_time}</Popover>
          </>
        );
      },
    },
    {
      title: '操作',
      width: 50,
      align: 'center',
      key: 'option1',
      fixed: 'right',
      valueType: 'option',
      render: (_, data) => {
        return (
          <a key='link' onClick={handleDetail.bind(null, { id: data.id })}>
            查看详情
          </a>
        );
      },
    },
  ];

  const requestTableData = async (values: any) => {
    const { current: page, pageSize: size, ...rest } = values;
    const reqData: {
      page: number;
      size: number;
      type?: number;
    } = {
      page,
      size,
      type: 1,
      ...rest,
    };
    if (type === 'adopt') {
      reqData.type = 2;
    } else if (type === 'disable') {
      reqData.type = 3;
    }
    const { code, data, msg } = await getApplicationList(reqData);
    if (code == 0) {
      return { data: data.list, total: data.total };
    } else {
      message.error(msg);
    }
  };

  useEffect(() => {
    if (activeKey !== type) return;
    actionRef.current?.reload();
  }, [activeKey, type]);

  return (
    <>
      <DragTable>
        <ProTable<TableListItem>
          actionRef={actionRef}
          rowKey='id'
          className='kb-pro-table'
          request={requestTableData as any}
          columns={columns}
          options={false}
          pagination={{
            pageSize: 20,
            showQuickJumper: false,
            showSizeChanger: false,
          }}
          scroll={{ x: 1300 }}
          search={{
            className: 'kb-pro-table-form',
            labelWidth: 'auto',
            collapseRender: () => false,
            optionRender: (_, { form }) => [
              <Button
                key='phone'
                type='primary'
                onClick={() => {
                  form?.submit();
                }}
              >
                搜索
              </Button>,
            ],
          }}
        />
      </DragTable>
      <Drawer
        visible={visible}
        width={winSize === 'xs' ? 300 : 700}
        closable={false}
        onClose={onClose}
        title='驿站详情'
      >
        <Spin spinning={submitLoading}>
          {record.inn_info ? (
            <>
              <Divider orientation='left'>驿站基础信息</Divider>
              <ProDescriptions>
                <ProDescriptions.Item span={12} label='驿站名称'>
                  {record.inn_info.inn_name}
                </ProDescriptions.Item>
                <ProDescriptions.Item span={12} label='驿站地址'>
                  {record.inn_info.full_location}
                </ProDescriptions.Item>
                <ProDescriptions.Item span={12} label='驿站账号'>
                  {record.inn_info.phone}
                </ProDescriptions.Item>
                <ProDescriptions.Item span={12} label='联系电话'>
                  {record.inn_info.concat_phone}
                </ProDescriptions.Item>
                <ProDescriptions.Item span={12} label='注册时间' valueType='dateTime'>
                  {record.inn_info.register_time}
                </ProDescriptions.Item>
                <ProDescriptions.Item span={12} label='申请时间' valueType='dateTime'>
                  {record.inn_info.apply_time}
                </ProDescriptions.Item>
                <ProDescriptions.Item span={12} label='实名认证'>
                  {record.inn_info.is_auth_realname == 1
                    ? '已实名'
                    : record.inn_info.is_auth_realname == 0
                    ? '未实名'
                    : '-'}
                </ProDescriptions.Item>
                <ProDescriptions.Item span={12} label='经营信息'>
                  {record.inn_info.business_audit_status === 0 ? (
                    '未提交'
                  ) : (
                    <a
                      href={`http://admin.kuaidihelp.com/f/yz/innAuditDetailt?type=${record.inn_info.business_audit_status}&cm_id=${record.inn_info.cm_id}`}
                    >
                      {record.inn_info.business_audit_status === 1
                        ? '待审核'
                        : record.inn_info.business_audit_status === 2
                        ? '未通过'
                        : record.inn_info.business_audit_status === 3
                        ? '已通过'
                        : '-'}
                    </a>
                  )}
                </ProDescriptions.Item>
              </ProDescriptions>
            </>
          ) : null}
          {record.inn_stat ? (
            <>
              <Divider orientation='left'>驿站出入库统计</Divider>
              <DragTable>
                <ProTable
                  className='kb-pro-table'
                  dataSource={[record.inn_stat]}
                  columns={recordColumns}
                  size='middle'
                  search={false}
                  rowKey='id'
                  pagination={false}
                  options={false}
                  scroll={{ x: 1200 }}
                />
              </DragTable>
            </>
          ) : null}
          <Divider orientation='left'>驿站操作记录</Divider>
          {yzLogList.list.length > 0
            ? yzLogList.list.map((item: any) => {
                return (
                  <Row key={item.id}>
                    <Col span={6}>{item.create_time}</Col>
                    <Col span={18}>{item.content}</Col>
                  </Row>
                );
              })
            : null}
          {
            <Space style={{ display: 'flex', justifyContent: 'center', margin: 20 }}>
              {yzLogList.hasNextPage ? (
                <a onClick={() => getYzLog({ cm_id: record.inn_info.cm_id })}>更多</a>
              ) : (
                '加载完毕'
              )}
            </Space>
          }
          {showButton && (
            <Row
              justify='center'
              gutter={[40, 0]}
              style={{
                padding: '50px 0',
              }}
            >
              <Col>
                <Button type='primary' key='agree' onClick={() => handleSubmit({ is_approved: 1 })}>
                  通过
                </Button>
              </Col>
              <Col>
                <Button danger key='refuse' onClick={() => setFormVisible(true)}>
                  驳回
                </Button>
              </Col>
            </Row>
          )}
        </Spin>

        <div
          style={{
            position: 'absolute',
            right: 0,
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e9e9e9',
            padding: '10px 16px',
            background: '#fff',
            textAlign: 'right',
          }}
        >
          <Button
            type='ghost'
            style={{ marginRight: 8 }}
            onClick={() =>
              handleDetail({
                page_turn: 'next',
                id: record.inn_info.id,
              })
            }
          >
            查看上一条
          </Button>
          <Button
            type='primary'
            onClick={() =>
              handleDetail({
                page_turn: 'prev',
                id: record.inn_info.id,
              })
            }
          >
            查看下一条
          </Button>
        </div>
      </Drawer>
      <KbRefuseModal onCancel={handleHideMoal} visible={formVisible} onOk={handleSubmit} />
    </>
  );
};

export default ChangeInfoTable;
